package com.axend.aerosense.main;

import android.content.Context;

import com.axend.aerosense.base.utils.SystemUtil;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.network.model.HttpHeaders;
import com.tencent.mmkv.MMKV;
import com.axend.aerosense.base.app.BaseApplication;
import com.axend.aerosense.base.impl.IModuleInit;
import com.axend.aerosense.base.utils.LogUtils;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.converter.GsonDiskConverter;
import com.axend.aerosense.network.cache.model.CacheMode;

import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.TrustManagerFactory;

/**
 * @author ChenHongWei
 * @date :2020/12/15 16:54
 */

public class MainModuleInit implements IModuleInit {

    private String baseUrl = UrlApi.getBaseUrl();

    @Override
    public boolean onInitAhead(BaseApplication application) {
        //初始化MMKV
        MMKV.initialize(application);
        //初始化网络模块
        EasyHttp.init(application);
        if (application.issDebug())
        {
            EasyHttp.getInstance().debug("EasyHttp", true);
        }
        EasyHttp.getInstance()
                .setBaseUrl(baseUrl)
                .setReadTimeOut(30 * 1000)
                .setWriteTimeOut(30 * 1000)
                .setConnectTimeout(30 * 1000)
                .setRetryCount(2)
                .setCacheDiskConverter(new GsonDiskConverter())
                .setCacheMode(CacheMode.FIRSTREMOTE);
        EasyHttp.getInstance().setCertificates();
        HttpHeaders commonHeaders = new HttpHeaders();
        commonHeaders.put(EasyHttp.TIME_ZONE, "GMT" + SystemUtil.getTimeZone().getRoomTimeZone());
        commonHeaders.put(EasyHttp.ACCEPT_TIME_ZONE, "GMT" + SystemUtil.getTimeZone().getRoomTimeZone());
        commonHeaders.put("language", SystemUtil.getSystemLanguage());
        EasyHttp.getInstance().addCommonHeaders(commonHeaders);
        LogUtils.d(this, "MainModuleInit 模块初始化成功！");
        return false;
    }

    @Override
    public boolean onInitLow(BaseApplication application) {
        return false;
    }

    public static InputStream getSSLContext(Context context) {
        CertificateFactory certificateFactory = null;
        InputStream inputStream = null;
        Certificate cer = null;
        TrustManagerFactory trustManagerFactory = null;

        try {
            certificateFactory = CertificateFactory.getInstance("X.509");
            inputStream = context.getAssets().open("ax.cer");//这里导入SSL证书文件
//            cer = certificateFactory.generateCertificate(inputStream);
        }catch (Exception e){

        }

        return inputStream;
    }
}
